package fr.isima.myanttest;

import static org.junit.Assert.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import fr.isima.myant.Project;

public class CopyTest {
	Project p;
	
	@Before
	public void beforeExecute() {
		try{
			p = new Project("testCopy.txt");
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	@Test
	public void testExecute() {
		p.execute("testcopy");
		
		try {
			assertEquals(getMD5Checksum("fromFile.bin"), getMD5Checksum("toFile.bin"));
		} catch (Exception e) {
			fail(e.getMessage());
		}
	}
	
	@After
	public void after() {
		Path filePathTo = Paths.get("toFile.bin");
		try {
			Files.delete(filePathTo);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	
	   public static byte[] createChecksum(String filename) throws Exception {
	       InputStream fis =  new FileInputStream(filename);

	       byte[] buffer = new byte[1024];
	       MessageDigest complete = MessageDigest.getInstance("MD5");
	       int numRead;

	       do {
	           numRead = fis.read(buffer);
	           if (numRead > 0) {
	               complete.update(buffer, 0, numRead);
	           }
	       } while (numRead != -1);

	       fis.close();
	       return complete.digest();
	   }

	   // see this How-to for a faster way to convert
	   // a byte array to a HEX string
	   public static String getMD5Checksum(String filename) throws Exception {
	       byte[] b = createChecksum(filename);
	       String result = "";

	       for (int i=0; i < b.length; i++) {
	           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
	       }
	       return result;
	   }
	
}
